import { BrowserWindow, ipcMain, session, dialog, shell } from "electron";
import { readFile } from "node:fs";
import $http from "./http";
import { createWindow } from "./utils";
import { startListenBlive, stopListenBlive } from "./blive";

ipcMain.on("title:set", (event, title) => {
  const webContents = event.sender;
  const win = BrowserWindow.fromWebContents(webContents);
  win.setTitle(title);
});
ipcMain.handle("cookie:get", (event, filter) => {
  const webContents = event.sender;
  const ses = session.defaultSession;
  return ses.cookies.get(filter);
});
ipcMain.handle("cookie:set", (event, details) => {
  const webContents = event.sender;
  const ses = webContents.session;
  return ses.cookies.set(details);
});
ipcMain.handle("cookie:remove", (event, url, name) => {
  const webContents = event.sender;
  const ses = session.defaultSession;
  return ses.cookies.remove(url, name);
});
ipcMain.handle("cookie:clear", (event, url) => {
  const webContents = event.sender;
  const ses = session.defaultSession;
  return new Promise((resolve, reject) => {
    ses.cookies.get({ url }).then(async data => {
      for (let v of data) {
        await ses.cookies.remove(url, v.name);
      }
      resolve(data);
    });
  });
});
ipcMain.handle("window:create", (event, hash, opt) => {
  const win = createWindow(hash, opt);
  return new Promise((resolve, reject) => {
    win.webContents.on("did-finish-load", () => {
      resolve("did-finish-load");
    });
  });
});
ipcMain.handle("blive:start", (event, roomId) => {
  return startListenBlive(roomId);
});
ipcMain.handle("blive:stop", (event, roomId) => {
  return stopListenBlive();
});
ipcMain.handle("axios", (event, opt) => {
  const webContents = event.sender;
  const ses = webContents.session;
  if (opt.loading) webContents.send("screen:loading", true);
  return $http(opt)
    .then((res: any) => {
      if ([200, 0].includes(res.code)) {
        return Promise.resolve(res.data);
      } else {
        webContents.send("screen:message", "error", res.message);
        return Promise.reject(res);
      }
    })
    .finally(() => {
      if (opt.loading) webContents.send("screen:loading", false);
    });
});
ipcMain.handle("dialog:open", (event, opt) => {
  return dialog.showOpenDialogSync(
    Object.assign(
      {
        properties: ["openFile", "multiSelections"]
      },
      opt
    )
  );
});
ipcMain.handle("file:read", (event, path) => {
  return new Promise((resolve, reject) => {
    readFile(path, "base64", (err, data) => {
      if (err) reject(err);
      resolve(data);
    });
  });
});
ipcMain.handle("shell:open", (event, url) => {
  return shell.openExternal(url);
});
ipcMain.handle("args:get", (event, name) => {
  const args = process.argv.reduce((acc, curr) => {
    const arr = curr.split("=");
    if (arr.length < 2) return acc;
    acc[arr[0]] = arr[1];
    return acc;
  }, {});
  return new Promise((resolve, reject) => {
    resolve(name ? args[name] : args);
  });
});
